package com.chookss.mine.set;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.audit.adapter.UserInfoDocunmentListAdapter;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.publish.UploadUserImageService;
import com.chookss.mine.entity.MineInfoEntity;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.GridSpacingItemDecoration;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.bigImage.ImagePreview;
import com.chookss.tools.bigImage.bean.ImageInfo;
import com.chookss.tools.filePicker.FilePicker;
import com.chookss.tools.filePicker.model.EssFile;
import com.chookss.tools.filePicker.util.Const;
import com.chookss.tools.filePicker.util.FileSizeUtil;
import com.chookss.tools.filePicker.util.FileUtils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.DrawableTextView;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.InitDialog;
import com.chookss.view.LogBottomDialog;
import com.chookss.view.MyRoundLayout;
import com.chookss.view.listener.HomeBottomDialogListener;
import com.chookss.view.listener.ShareDialogListener;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RealNameActivity extends BaseAct {

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_txt)
    TextView commonRightTxt;
    @BindView(R.id.tvRealName)
    TextView tvRealName;
    @BindView(R.id.edIdentityCard)
    EditText edIdentityCard;
    @BindView(R.id.edBankType)
    EditText edBankType;
    @BindView(R.id.edBankAddress)
    EditText edBankAddress;
    @BindView(R.id.edBankCard)
    EditText edBankCard;
    @BindView(R.id.fileCredentialsRcv)
    RecyclerView fileCredentialsRcv;
    @BindView(R.id.fileEducationRcv)
    RecyclerView fileEducationRcv;
    @BindView(R.id.fileCertificateRcv)
    RecyclerView fileCertificateRcv;
    @BindView(R.id.fileCredentialsRcvSpace)
    View fileCredentialsRcvSpace;
    @BindView(R.id.fileEducationRcvSpace)
    View fileEducationRcvSpace;
    @BindView(R.id.fileCertificateRcvSpace)
    View fileCertificateRcvSpace;
    @BindView(R.id.tvCredentials)
    DrawableTextView tvCredentials;
    @BindView(R.id.tvEducation)
    DrawableTextView tvEducation;
    @BindView(R.id.tvCertificate)
    DrawableTextView tvCertificate;
    @BindView(R.id.tvContract)
    DrawableTextView tvContract;
    @BindView(R.id.fileContractImgRcv)
    RecyclerView fileContractImgRcv;
    @BindView(R.id.fileContractDocRcv)
    RecyclerView fileContractDocRcv;
    @BindView(R.id.fileContractDocRcvSpace)
    View fileContractDocRcvSpace;
    @BindView(R.id.fileContractRcvSpace)
    View fileContractRcvSpace;
    @BindView(R.id.tvContractTime)
    TextView tvContractTime;
    @BindView(R.id.llContractTime)
    LinearLayout llContractTime;
    @BindView(R.id.ivContractTime)
    ImageView ivContractTime;
    private static final int REQUEST_CODE_CHOOSE = 34;
    private MyImagsAdapter credentialsAdapter, educationAdapter, certificateAdapter,contractAdapter;
    private UserInfoDocunmentListAdapter docunmentListAdapter;
    private List<String> credentialsList = null;
    private List<String> educationList = null;
    private List<String> certificateList = null;
    private List<String> contractList = null;
    private List<MineInfoEntity.DatabaseBean> contractDocList = new ArrayList<>();
    private int choiceImg = -1;//选择哪一个模块选择照片
    private MineInfoEntity mineInfoEntity = null;
    private String[] contractTimeArray = null;
    private boolean isEdit = false;//默认是展示状态
    private String tag = "RealNameActivity_DownloadFile";//下载文件打的标签
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_real_name);
        ButterKnife.bind(this);
        NavigationTools.setWaterMark(this, "18");
    }

    @Override
    public void initData() {
        initState();
        commonTitleTxt.setText("实名认证");
        commonRightTxt.setText("修改");
        commonRightTxt.setVisibility(View.VISIBLE);
        contractTimeArray = new String[]{"1年", "2年", "3年", "4年", "5年", "6年", "7年", "8年", "9年", "10年", "长期"};
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 3);
        fileCredentialsRcv.setLayoutManager(gridLayoutManager1);
        GridSpacingItemDecoration gridSpacingItemDecoration = new GridSpacingItemDecoration(3, Utils.dip2px(this, 12), false);
        fileCredentialsRcv.addItemDecoration(gridSpacingItemDecoration);


        GridLayoutManager gridLayoutManager2 = new GridLayoutManager(this, 3);
        fileEducationRcv.setLayoutManager(gridLayoutManager2);
        GridSpacingItemDecoration gridSpacingItemDecoration2 = new GridSpacingItemDecoration(3, Utils.dip2px(this, 12), false);
        fileEducationRcv.addItemDecoration(gridSpacingItemDecoration2);

        GridLayoutManager gridLayoutManager3 = new GridLayoutManager(this, 3);
        fileCertificateRcv.setLayoutManager(gridLayoutManager3);
        GridSpacingItemDecoration gridSpacingItemDecoration3 = new GridSpacingItemDecoration(3, Utils.dip2px(this, 12), false);
        fileCertificateRcv.addItemDecoration(gridSpacingItemDecoration3);

        GridLayoutManager gridLayoutManager4 = new GridLayoutManager(this, 3);
        fileContractImgRcv.setLayoutManager(gridLayoutManager4);
        GridSpacingItemDecoration gridSpacingItemDecoration4 = new GridSpacingItemDecoration(3, Utils.dip2px(this, 12), false);
        fileContractImgRcv.addItemDecoration(gridSpacingItemDecoration4);

        fileContractDocRcv.setLayoutManager(new LinearLayoutManager(this));
        docunmentListAdapter = new UserInfoDocunmentListAdapter(R.layout.item_file_list, this,contractDocList, isEdit,  tag);
        fileContractDocRcv.setAdapter(docunmentListAdapter);
        selectEmployeeDetail();
        initEdtiStatus();
        registerBoradcastReceiver();
    }

    private void initEdtiStatus() {
        setEdit(edBankType, isEdit);
        setEdit(edBankAddress, isEdit);
        setEdit(edBankCard, isEdit);
        setEdit(edIdentityCard, isEdit);
        if (isEdit) {
            tvCredentials.setVisibility(View.VISIBLE);
            tvEducation.setVisibility(View.VISIBLE);
            tvCertificate.setVisibility(View.VISIBLE);
            tvContract.setVisibility(View.VISIBLE);
            if (!Utils.isNull(edIdentityCard.getText().toString())) {
                edIdentityCard.setSelection(edIdentityCard.getText().toString().length()); //光标移到最后
            }
            if (credentialsAdapter != null) {
                ivContractTime.setVisibility(View.VISIBLE);
                credentialsAdapter.notifyDataSetChanged();
                educationAdapter.notifyDataSetChanged();
                certificateAdapter.notifyDataSetChanged();
                contractAdapter.notifyDataSetChanged();
                docunmentListAdapter.setEdit(isEdit);
                docunmentListAdapter.notifyDataSetChanged();
            }
        }
    }

    private void setEdit(EditText editText, boolean focus) {
        if (focus) {
            editText.setFocusableInTouchMode(true);
            editText.setFocusable(true);
            editText.requestFocus();
        } else {
            editText.setFocusable(false);
            editText.setFocusableInTouchMode(false);
        }
    }

    private void selectEmployeeDetail() {
        Map<String, String> map = new HashMap<>();
        map.put("employeeCode", new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        map.put("type", "1");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<MineInfoEntity>>() {
        }.getType(), null, Urls.selectEmployeeDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<MineInfoEntity>() {
            @Override
            public void onSuccess(MineInfoEntity data) throws Exception {
                mineInfoEntity = data;
                tvRealName.setText(mineInfoEntity.getEmployeeName());
                edIdentityCard.setText(mineInfoEntity.getRegisteredNumber());
                edBankType.setText(mineInfoEntity.getBankName());
                edBankAddress.setText(mineInfoEntity.getBankAddress());
                edBankCard.setText(mineInfoEntity.getBankNumber());
                tvContractTime.setText(mineInfoEntity.getContractLength());
                //证件
                if (Utils.isNull(mineInfoEntity.getRegisteredImage())) {
                    credentialsList = new ArrayList<>();
                } else {
                    fileCredentialsRcv.setVisibility(View.VISIBLE);
                    fileCredentialsRcvSpace.setVisibility(View.VISIBLE);
                    credentialsList = new ArrayList<>(Arrays.asList(mineInfoEntity.getRegisteredImage().split(",")));
                }

                //学历
                if (Utils.isNull(mineInfoEntity.getEducationImage())) {
                    educationList = new ArrayList<>();
                } else {
                    fileEducationRcv.setVisibility(View.VISIBLE);
                    fileEducationRcvSpace.setVisibility(View.VISIBLE);
                    educationList = new ArrayList<>(Arrays.asList(mineInfoEntity.getEducationImage().split(",")));
                }

                //证书
                if (Utils.isNull(mineInfoEntity.getCertificateImage())) {
                    certificateList = new ArrayList<>();
                } else {
                    fileCertificateRcv.setVisibility(View.VISIBLE);
                    fileCertificateRcvSpace.setVisibility(View.VISIBLE);
                    certificateList = new ArrayList<>(Arrays.asList(mineInfoEntity.getCertificateImage().split(",")));
                }
                //合同
                if (Utils.isNull(mineInfoEntity.getContractImage())) {
                    contractList = new ArrayList<>();
                } else {
                    fileContractImgRcv.setVisibility(View.VISIBLE);
                    fileContractDocRcvSpace.setVisibility(View.VISIBLE);
                    contractList = new ArrayList<>(Arrays.asList(mineInfoEntity.getContractImage().split(",")));
                }
                if (!Utils.isNull(mineInfoEntity.getContractFile())) {
                    getDocunmentDetail(mineInfoEntity.getContractFile());
                }
                initAdapter();
            }

            @Override
            public void onError(String errorMsg) {
                initAdapter();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void getDocunmentDetail(String dataCode) {
        Map<String, String> map = new HashMap<>();
        map.put("dataCode",dataCode);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<MineInfoEntity.DatabaseBean>>>() {
        }.getType(), null, Urls.getDetailList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<MineInfoEntity.DatabaseBean>>() {
            @Override
            public void onSuccess(List<MineInfoEntity.DatabaseBean> data) {
                if (data != null) {
                    contractDocList.clear();
                    contractDocList.addAll(data);
                    fileContractDocRcv.setVisibility(View.VISIBLE);
                    fileContractRcvSpace.setVisibility(View.VISIBLE);
                    docunmentListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void initAdapter() {
        if (credentialsList == null) {
            credentialsList = new ArrayList<>();
        }
        if (educationList == null) {
            educationList = new ArrayList<>();
        }
        if (certificateList == null) {
            certificateList = new ArrayList<>();
        }
        if (contractList == null) {
            contractList = new ArrayList<>();
        }
        credentialsAdapter = new MyImagsAdapter(R.layout.item_my_news, RealNameActivity.this, credentialsList, 1);
        fileCredentialsRcv.setAdapter(credentialsAdapter);
        educationAdapter = new MyImagsAdapter(R.layout.item_my_news, RealNameActivity.this, educationList, 2);
        fileEducationRcv.setAdapter(educationAdapter);
        certificateAdapter = new MyImagsAdapter(R.layout.item_my_news, RealNameActivity.this, certificateList, 3);
        fileCertificateRcv.setAdapter(certificateAdapter);
        contractAdapter = new MyImagsAdapter(R.layout.item_my_news, RealNameActivity.this, contractList, 4);
        fileContractImgRcv.setAdapter(contractAdapter);
    }

    private void uploadFile() {
        if (mineInfoEntity == null) {
            MyToast.show("服务器异常，请稍后重试");
            return;
        }
        if (credentialsList == null || educationList == null || certificateList == null||contractList==null) {
            return;
        }
        Intent intent = new Intent(this, UploadUserImageService.class);
        mineInfoEntity.setRegisteredNumber(edIdentityCard.getText().toString());
        mineInfoEntity.setBankName(edBankType.getText().toString());
        mineInfoEntity.setBankAddress(edBankAddress.getText().toString());
        mineInfoEntity.setBankNumber(edBankCard.getText().toString());
        mineInfoEntity.setRegisteredImageList(credentialsList);
        mineInfoEntity.setEducationImageList(educationList);
        mineInfoEntity.setCertificateImageList(certificateList);
        mineInfoEntity.setContractImageList(contractList);
        mineInfoEntity.setDatabase(contractDocList);
        mineInfoEntity.setContractLength(tvContractTime.getText().toString());
        intent.putExtra("mineInfoEntity", mineInfoEntity);
        startService(intent);
        finish();
    }

    private void deleteImg(int type, int position) {
        if (type == 1) {
            credentialsList.remove(position);
            credentialsAdapter.notifyDataSetChanged();
            if (credentialsList.size() == 0) {
                fileCredentialsRcv.setVisibility(View.GONE);
                fileCredentialsRcvSpace.setVisibility(View.GONE);
            }
        } else if (type == 2) {
            educationList.remove(position);
            educationAdapter.notifyDataSetChanged();
            if (educationList.size() == 0) {
                fileEducationRcv.setVisibility(View.GONE);
                fileEducationRcvSpace.setVisibility(View.GONE);
            }
        } else if (type == 3) {
            certificateList.remove(position);
            certificateAdapter.notifyDataSetChanged();
            if (certificateList.size() == 0) {
                fileCertificateRcv.setVisibility(View.GONE);
                fileCertificateRcvSpace.setVisibility(View.GONE);
            }
        }else if (type == 4) {
            contractDocList.remove(position);
            docunmentListAdapter.notifyDataSetChanged();
            if (contractDocList.size() == 0) {
                fileContractDocRcv.setVisibility(View.GONE);
                fileContractRcvSpace.setVisibility(View.GONE);
            }
        }

    }

    class MyImagsAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Context context;
        private int imgType, width, height;

        public MyImagsAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<String> data, int imgType) {
            super(layoutResId, data);
            this.context = context;
            this.width = (Utils.getScreenWidthPixel(context) - Utils.dip2px(context, 48)) / 3;
            this.height = width;
            this.imgType = imgType;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String item) {
            MyRoundLayout myRl = helper.getView(R.id.myRl);
            ImageView ivBg = helper.getView(R.id.ivBg);
            LinearLayout llDelete = helper.getView(R.id.llDelete);
            LinearLayout llAdd = helper.getView(R.id.llAdd);
            llAdd.setVisibility(View.GONE);
            myRl.setVisibility(View.VISIBLE);
            if (isEdit) {
                llDelete.setVisibility(View.VISIBLE);
            } else {
                llDelete.setVisibility(View.GONE);
            }
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) myRl.getLayoutParams();
            params.height = height;
            params.width = width;
            myRl.setLayoutParams(params);
            Glide.with(RealNameActivity.this).load(item).into(ivBg);
            llDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new InitDialog(RealNameActivity.this,
                            "提示", "确定要删除么？", "确定", true,
                            new ShareDialogListener() {
                                @Override
                                public void onClick() {
                                    deleteImg(imgType, helper.getItemPosition());
                                }
                            }).show();

                }
            });
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setPicUrlList(imgType, helper.getItemPosition());
                }
            });
        }
    }

    private void setPicUrlList(int type, int position) {
        List<ImageInfo> imageInfoList = new ArrayList<>();
        List<String> imgList = new ArrayList<>();
        if (type == 1) {
            imgList.addAll(credentialsList);
        } else if (type == 2) {
            imgList.addAll(educationList);
        } else if (type == 3) {
            imgList.addAll(certificateList);
        } else if (type == 4) {
            imgList.addAll(contractList);
        }
        for (int i = 0; i < imgList.size(); i++) {
            ImageInfo imageInfo = new ImageInfo();
            if (imgList.get(i).contains("x-oss-process")) {
                imageInfo.setThumbnailUrl(imgList.get(i).split("\\?")[0]);// 缩略图url
                imageInfo.setOriginUrl(imgList.get(i).split("\\?")[0]);// 原图url
            } else {
                imageInfo.setOriginUrl(imgList.get(i));// 原图url
                imageInfo.setThumbnailUrl(imgList.get(i));// 缩略图url
            }
            imageInfoList.add(imageInfo);
        }
        ImagePreview
                .getInstance()
                // 上下文，必须是activity，不需要担心内存泄漏，本框架已经处理好；
                .setContext(this)
                // 设置从第几张开始看（索引从0开始）
                .setIndex(position)
                .setShowCloseButton(true)
                .setLoadStrategy(ImagePreview.LoadStrategy.NetworkAuto)
                .setImageInfoList(imageInfoList)
                .start();
    }

    private void requestCamera(int type, int size) {
        //图片
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            if (type == 0) {
                                PictureSelector.create(RealNameActivity.this)
                                        .openGallery(SelectMimeType.ofImage())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxSelectNum(size)
                                        .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                        .isPreviewImage(true)//是否支持预览图片
                                        .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                            } else {
                                //文档
                                FilePicker
                                        .from(RealNameActivity.this)
                                        .chooseForMimeType()
                                        .setMaxCount(size)
                                        .setFileTypes("pdf", "doc", "ppt", "xls")
                                        .requestCode(REQUEST_CODE_CHOOSE)
                                        .start();
                            }
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(RealNameActivity.this, denied, quick);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 如果是直接从相册获取
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    if (choiceImg == 1) {
                        if (!credentialsList.contains(url)) {
                            credentialsList.add(url);
                        }
                    } else if (choiceImg == 2) {
                        if (!educationList.contains(url)) {
                            educationList.add(url);
                        }
                    } else if (choiceImg == 3) {
                        if (!certificateList.contains(url)) {
                            certificateList.add(url);
                        }
                    } else if (choiceImg == 4) {
                        if (!contractList.contains(url)) {
                            contractList.add(url);
                        }
                    }
                }
                if (choiceImg == 1) {
                    fileCredentialsRcv.setVisibility(View.VISIBLE);
                    fileCredentialsRcvSpace.setVisibility(View.VISIBLE);
                    credentialsAdapter.notifyDataSetChanged();
                } else if (choiceImg == 2) {
                    fileEducationRcv.setVisibility(View.VISIBLE);
                    fileEducationRcvSpace.setVisibility(View.VISIBLE);
                    educationAdapter.notifyDataSetChanged();
                } else if (choiceImg == 3) {
                    fileCertificateRcv.setVisibility(View.VISIBLE);
                    fileCertificateRcvSpace.setVisibility(View.VISIBLE);
                    certificateAdapter.notifyDataSetChanged();
                }else if (choiceImg == 4) {
                    fileContractImgRcv.setVisibility(View.VISIBLE);
                    fileContractDocRcvSpace.setVisibility(View.VISIBLE);
                    contractAdapter.notifyDataSetChanged();
                }
            }
            if (requestCode == REQUEST_CODE_CHOOSE) {
                //文档选择
                ArrayList<EssFile> essFileList = data.getParcelableArrayListExtra(Const.EXTRA_RESULT_SELECTION);
                if (essFileList.size() != 0) {
                    for (int i = 0; i < essFileList.size(); i++) {
                        MineInfoEntity.DatabaseBean docunmentEntity = new MineInfoEntity.DatabaseBean();
                        docunmentEntity.setDataTitle(essFileList.get(i).getName());
                        docunmentEntity.setDataCode("");
                        docunmentEntity.setDataPath(essFileList.get(i).getAbsolutePath());
                        docunmentEntity.setUploadTime(FileUtils.getDateTime(essFileList.get(i).getAbsolutePath()));
                        docunmentEntity.setDataSize(FileSizeUtil.getAutoFileOrFilesSize((essFileList.get(i).getFile())));
                        contractDocList.add(docunmentEntity);
                        KLog.i(essFileList.get(i).getAbsolutePath());
                    }

                } else {
                    KLog.i("essFileList.size() == 0");
                }
                if (contractDocList.size() > 0) {
                    fileContractDocRcv.setVisibility(View.VISIBLE);
                    fileContractRcvSpace.setVisibility(View.VISIBLE);
                    docunmentListAdapter.notifyDataSetChanged();
                }
            }
        }

    }

    @OnClick({R.id.common_title_back, R.id.llContractTime, R.id.tvContract, R.id.common_right_txt, R.id.tvCredentials, R.id.tvEducation, R.id.tvCertificate})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.llContractTime:
                if(!isEdit){
                    return;
                }
                new XPopup.Builder(RealNameActivity.this)
                        .maxWidth(Utils.dip2px(RealNameActivity.this, 260))
                        .maxHeight(Utils.dip2px(RealNameActivity.this, 300))
                        .asCenterList("请选择劳务合同期限", contractTimeArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        tvContractTime.setText(text);
                                    }
                                })
                        .show();
                break;
            case R.id.tvContract:
                new LogBottomDialog(this, false, new HomeBottomDialogListener() {
                    @Override
                    public void onListItemClick(int position) {
                        if (position == 0) {
                            choiceImg = 4;
                            requestCamera(0, 10 - contractList.size());
                        } else if (position == 2) {
                            requestCamera(1, 10-contractDocList.size());
                        }
                    }
                }).show();
                break;
            case R.id.common_right_txt:
                if (isEdit) {
                    new InitDialog(RealNameActivity.this,
                            "提示", "确定要修改么？", "确定", true,
                            new ShareDialogListener() {
                                @Override
                                public void onClick() {
                                    uploadFile();
                                }
                            }).show();
                } else {
                    isEdit = true;
                    commonRightTxt.setText("保存");
                    initEdtiStatus();
                }

                break;
            case R.id.tvCredentials:
                //证件
                if (credentialsList.size() >= 10) {
                    MyToast.show("最多上传10张");
                    return;
                } else {
                    choiceImg = 1;
                    requestCamera(0, 10 - credentialsList.size());
                }
                break;
            case R.id.tvEducation:
                //学历
                if (educationList.size() >= 10) {
                    MyToast.show("最多上传10张");
                    return;
                } else {
                    choiceImg = 2;
                    requestCamera(0, 10 - educationList.size());
                }
                break;
            case R.id.tvCertificate:
                //证书
                if (certificateList.size() >= 10) {
                    MyToast.show("最多上传10张");
                    return;
                } else {
                    choiceImg = 3;
                    requestCamera(0, 10 - certificateList.size());
                }
                break;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("deleteDocunment")) {
                int position = Utils.changeNumber(map.get("position"));
                if (position >= 0) {
                    contractDocList.remove(position);
                    docunmentListAdapter.notifyDataSetChanged();
                    if(contractDocList.size()==0){
                        fileContractDocRcv.setVisibility(View.GONE);
                        fileContractRcvSpace.setVisibility(View.GONE);
                    }
                }
            }

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
        }
    }
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && intent.getAction() != null) {
                String action = intent.getAction();
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                for (int i = 0; i <contractDocList.size(); i++) {
                    if (contractDocList.get(i).getDataCode().equals(recevierDataCode)) {
                        if (!contractDocList.get(i).isOpen()) {
                            if (encryptStatus) {
                                contractDocList.get(i).setOpen(true);
                            }
                            dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                        }
                    }
                }
            }
        }

    };

    /**
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("secret", true);
                startActivity(newIntent);
            }
        } else {
            if (percent > 0 && percent < 100) {
                if (docunmentListAdapter != null) {
                    contractDocList.get(position).setProgress(percent);
                    docunmentListAdapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (docunmentListAdapter != null) {
                    contractDocList.get(position).setProgress(100);
                    docunmentListAdapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(RealNameActivity.this, fileUrl, fileName, recevierDataCode, tag);
                        }
                    }.start();
                }

            } else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                newIntent.putExtra("secret", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(tag);// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
    }

}
